package dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个整数 n ，按字典序返回范围 [1, n] 内所有整数。
 * 你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
 * <p>
 * 示例 1：
 * 输入：n = 13
 * 输出：[1,10,11,12,13,2,3,4,5,6,7,8,9]
 * <p>
 * 示例 2：
 * 输入：n = 2
 * 输出：[1,2]
 *
 * @author Jisheng Huang
 * @version 20250608
 */
public class LexicographicalNumbers_386 {
    /**
     * @param n the given integer n
     * @return the list of the lexicographical order
     */
    public static List<Integer> lexicalOrder(int n) {
        List<Integer> ret = new ArrayList<>();
        // Starting point
        // The first number will always be '1'
        // e.g. [1, ......]
        int number = 1;

        for (int i = 0; i < n; ++i) {
            ret.add(number);

            // dfs check whether you can get more number from the root number
            if (number * 10 <= n) {
                number *= 10;
            } else {
                // To find the endpoint
                while (number % 10 == 9 || number + 1 > n) {
                    number /= 10;
                }

                ++number;
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        List<Integer> ans = lexicalOrder(23);

        for (int i = 0; i < ans.size(); ++i) {
            System.out.print(ans.get(i) + " ");
        }

        System.out.println();

        ans = lexicalOrder(2);

        for (int i = 0; i < ans.size(); ++i) {
            System.out.println(ans.get(i) + " ");
        }
    }
}
